package com.ck.shiro;

import com.ck.cache.RedisCacheDao;
import com.ck.constant.CacheConstant;
import com.ck.dao.ModuleMapper;
import com.ck.dao.UserMapper;
import com.ck.model.common.User;
import com.ck.model.common.dto.ButtonModuleDTO;
import com.ck.model.common.dto.MenuModuleDTO;
import com.ck.model.common.vo.UserRoleSelectListVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 用户权限验证器
 *
 * @author linqiang
 * @version v1.0
 * @date 2018-09-13 11:56
 */
@Component
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ModuleMapper moduleMapper;

    private String auths =
            "P_B_program_add," +
                    "P_B_program_delete," +
                    "P_B_program_edit," +
                    "P_B_program_approve," +
                    "P_B_picture_group_add," +
                    "P_B_picture_group_edit," +
                    "P_B_picture_group_delete," +
                    "P_B_picture_change_group," +
                    "P_B_picture_delete," +
                    "P_B_picture_rename," +
                    "P_B_video_rename," +
                    "P_B_video_delete," +
                    "P_B_device_group_add," +
                    "P_B_device_group_edit," +
                    "P_B_device_group_delete," +
                    "P_B_device_change_group," +
                    "P_B_device_remote_shutdown," +
                    "P_B_device_time_switch_machine," +
                    "P_B_device_time_switch_screen," +
                    "P_B_device_reboot," +
                    "P_B_device_volume_setting," +
                    "P_B_device_detail," +
                    "P_B_device_untie";

    private List<String> authList = Arrays.asList(auths.split(","));

    /**
     * 授权 验证权限---->查询用户权限保存
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userName = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        if (StringUtils.isNotBlank(userName)) {
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            //从缓存获取用户按钮权限信息
            Object info = session.getAttribute(ShiroConstant.SESSION_PERMISSION_BUTTON + userName);
            if (null != info) {
                simpleAuthorizationInfo = (SimpleAuthorizationInfo) info;
            } else {
                User loginUser = userMapper.getUserByUserName(userName);
                //用户角色
                List<UserRoleSelectListVO> userRoleSelectListVOS = userMapper.listUserRoleName(loginUser.getUserId());
                for (UserRoleSelectListVO userRoleSelectListVO : userRoleSelectListVOS) {
                    simpleAuthorizationInfo.addRole(userRoleSelectListVO.getRoleName());
                }
                //权限
                ArrayList<String> permissions = new ArrayList<>();
                //用户按钮权限(如创建节目：P_B_program_add)
                List<ButtonModuleDTO> buttonModuleDTOS = moduleMapper.listButtonModuleByUserId(loginUser.getUserId());
                if (CollectionUtils.isNotEmpty(buttonModuleDTOS)) {
                    for (ButtonModuleDTO buttonModuleDTO : buttonModuleDTOS) {
                        if (StringUtils.isNotBlank(buttonModuleDTO.getUrl())) {
                            permissions.add(ShiroConstant.PERMISSION_PREFIX_BUTTON + buttonModuleDTO.getUrl());
                        }
                    }
                }
                simpleAuthorizationInfo.addStringPermissions(permissions);
                session.setAttribute(ShiroConstant.SESSION_PERMISSION_BUTTON + loginUser.getUserName(), simpleAuthorizationInfo);
            }
        }
        return simpleAuthorizationInfo;
    }

    /**
     * 用户身份验证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = (String) authenticationToken.getPrincipal();
        User loginUser = userMapper.getUserByUserName(userName);
        if (loginUser == null) {
            throw new UnknownAccountException("该用户不存在!");
        }
        return new SimpleAuthenticationInfo(loginUser.getUserName(), loginUser.getPassword(), this.getClass().getName());
    }
}
